package com.py.credit.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceBatchLogFieldsEnum;
import com.py.credit.entity.enums.ResourceLogQueryFieldsEnum;
import com.py.credit.service.BatchLogService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 入库日志查询
 * 
 * @author jicm
 * 
 */
@RestController
@RequestMapping(value = "/logQuery")
public class LogQueryController extends BaseController {

	private final static String FRONT_TABLE_ID = "logQuery";

	@Autowired
	private BatchLogService batchLogService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Autowired
	private RemoteBaseService remoteBaseService;

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(ResourceLogQueryFieldsEnum.getOptionalColumns());
	}

	/**
	 * 获取高级检索内容
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<>(ResourceLogQueryFieldsEnum.getAdvancedConditionColumns());
	}

	/**
	 * @api {get} /logQuery/getLogQueryList.json 获取导入批次信息列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 入库日志管理
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {String} type 类型 (选填)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":2,"data":[{"result":"F","deptName":"信用中心","start_time":1524827764000,"tcount":2,"rcount":2,"end_time":1524827764000,"scount":0,"id":"EX-10000060882-1-20180427-3813","type":"0","managerName":"超级管理员","fcount":0},{"result":"F","deptName":"信用中心","start_time":1524827530000,"tcount":2,"rcount":2,"end_time":1524827530000,"scount":0,"id":"EX-10000060882-1-20180427-7705","type":"0","managerName":"超级管理员","fcount":0}]}
	 * 
	 */
	@RequestMapping(value = "/getLogQueryList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "type", defaultValue = "", required = true) String type, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("LogQueryController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 列表数据
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceLogQueryFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
				showColumns.add("batchId");
		List<Map<String, Object>> tableList = batchLogService.getLogQueryListByConditionForPage(showColumns, null,
				condition, page, userInfo);
		RestServiceResult<List<Map<String, Object>>> userDept = new RestServiceResult<List<Map<String, Object>>>();
		if (!CollectionUtils.isEmpty(tableList)) {
			Set<Integer> userIds = new HashSet<Integer>();
			for (Map<String, Object> map : tableList) {
				if (null != map && null != map.get("managerId")) {
					userIds.add(Integer.parseInt(String.valueOf(map.get("managerId"))));
				}
			}
			// 填充用户名字
			tableList = remoteBaseService.matchUserDeptName(tableList, userDept,
					HttpServletHelper.getUserToken(request), userIds, "managerId", "managerName", "deptName");
			userDept.setCount(page.getTotalCount());
		}
		userDept.setData(tableList);
		return userDept;
	}

	/**
	 * 
	 * @api {get} /logQuery/export.json 入库日志导出
	 * @apiName export
	 * @apiVersion 0.0.1
	 * @apiGroup 入库日志管理
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@RequestMapping(value = "/export")
	public RestServiceResult<Object> export(
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		List<SysUser> userList = new ArrayList<>();
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#exportBookcontentList", "未获取到当前用户信息！");
				return result;
			}
			userList.add(userInfo);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 导出结果限制1000条
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		showColumns.add("deptId");
		showColumns.add("managerId");
		showColumns.add("target");
		List<Map<String, Object>> tableList = batchLogService.getLogQueryListByConditionForPage(showColumns, null,
				condition, page, userInfo);
		RestServiceResult<List<Map<String, Object>>> logQueryResult = new RestServiceResult<List<Map<String, Object>>>();
		try {
			if (!CollectionUtils.isEmpty(tableList)) {
				Set<Integer> userIds = new HashSet<Integer>();
				for (Map<String, Object> map : tableList) {
					if (null != map && null != map.get("managerId")) {
						userIds.add(Integer.parseInt(String.valueOf(map.get("managerId"))));
					}
				}
				// 填充用户名字
				tableList = remoteBaseService.matchUserDeptName(tableList, logQueryResult,
						HttpServletHelper.getUserToken(request), userIds, "managerId", "managerName", "deptName");
			}
			ExcelUtil.downloadExcel(response, tableList, "入库日志信息", "入库日志信息", showColumns,
					ResourceBatchLogFieldsEnum.getOptionalColumns());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("入库日志导出异常，请稍后再试！");
			ExceptionLogger.error("入库日志导出异常！", e.getMessage(), e);
			return result;
		}
	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("LogQueryController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
			String column = StringUtils.join(columns, ",");
			column = column + ",managerId" + ",deptId" + ",target";
			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return new RestServiceResult<String>();
	}

	/**
	 * 
	 * @api {get} /logQuery/logQueryData.json 获取入库日志查询图表数据
	 * @apiName logQueryData
	 * @apiVersion 0.0.1
	 * @apiGroup
	 * @apiParam {String} condition
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/logQueryData")
	public RestServiceResult<Map<String, Object>> logQueryData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			HttpServletRequest request, Page page) {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		Map<String, Object> resultData = new HashMap<String, Object>(3);
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("LogQueryController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 获取饼图数据
		Map<String, Object> bieTableList = batchLogService.getLogQueryBieByCondition(condition, userInfo);
		// 获取柱状图数据
		Map<String, Object> barTableList = batchLogService.logQueryBarView(userInfo);
		resultData.put("bieData", bieTableList);
		resultData.put("barData", barTableList);
		result.setData(resultData);
		return result;
	}
}
